package com.shawn.server.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shawn.commons.utils.RC;
import com.shawn.dubbo.api.RecommendUserApi;
import com.shawn.dubbo.api.VisitorsApi;
import com.shawn.model.mongo.RecommendUser;
import com.shawn.model.mongo.Visitors;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * @author shawn
 * @date 2022年 12月 08日 16:29
 */
@Slf4j
@Component
public class VisitorListener {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    /**
     * 侦听器访问者数据消息并保存
     *
     * @param message 消息
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = RC.MQ_VISITOR_QUEUE,durable = "true"),
            exchange = @Exchange(name = RC.MQ_VISITOR_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = RC.MQ_VISITOR_KEY
    ))
    public void listenerVisitorData(String message){
        log.info("接收到访客数据添加消息:{}",message);
        Map messageMap = JSON.parseObject(message, Map.class);
        Integer userId = (Integer) messageMap.get("userId");
        String from = (String) messageMap.get("from");
        Integer visitorId = (Integer) messageMap.get("visitorId");
        RecommendUser user =  recommendUserApi.findByBothId(Long.valueOf(userId),Long.valueOf(visitorId));
        if (user==null){
            //如果没有先构造缘分值95
            user= new RecommendUser();
            user.setScore(95D);
        }
        Visitors vi = new Visitors();
        vi.setDate(System.currentTimeMillis());
        vi.setScore(user.getScore());
        vi.setFrom(from);
        vi.setUserId(Long.valueOf(userId));
        vi.setVisitDate(new SimpleDateFormat(RC.VISITOR_DATE_FORMAT).format(System.currentTimeMillis()));
        vi.setVisitorUserId(Long.valueOf(visitorId));
        visitorsApi.save(vi);
    }
}
